<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>文件分片上传</title>
  </head>

  <body>
    <input type="file" id="fileInput" />
    <button onclick="uploadFile()">上传</button>

    <script>
      function uploadFile() {
        const fileInput = document.getElementById('fileInput')
        const file = fileInput.files[0]
        if (!file) {
          alert('请选择文件')
          return
        }

        const chunkSize = 1024 * 1024 // 每个分片 1MB
        const totalChunks = Math.ceil(file.size / chunkSize)
        const identifier = file.name + '_' + file.size

        let currentChunk = 0
        function uploadChunk() {
          const start = currentChunk * chunkSize
          const end = Math.min(start + chunkSize, file.size)
          const chunk = file.slice(start, end)

          const formData = new FormData()
          formData.append('file', chunk)
          formData.append('chunkNumber', currentChunk)
          formData.append('totalChunks', totalChunks)
          formData.append('identifier', identifier)

          const xhr = new XMLHttpRequest()
          xhr.open('POST', 'http://localhost:8080/file/uploadChunk', true)
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText)
                if (response.success) {
                  currentChunk++
                  if (currentChunk < totalChunks) {
                    uploadChunk()
                  } else {
                    mergeChunks()
                  }
                } else {
                  alert('分片上传失败: ' + response.message)
                }
              } else {
                alert('请求出错: ' + xhr.status)
              }
            }
          }
          xhr.send(formData)
        }

        function mergeChunks() {
          const xhr = new XMLHttpRequest()
          xhr.open('POST', 'http://localhost:8080/file/merge', true)
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText)
                if (response.success) {
                  alert('文件上传成功')
                } else {
                  alert('文件合并失败: ' + response.message)
                }
              } else {
                alert('请求出错: ' + xhr.status)
              }
            }
          }
          const data = `identifier=${identifier}&totalChunks=${totalChunks}`
          xhr.send(data)
        }

        uploadChunk()
      }
    </script>
  </body>
</html>
